package com.engine.kq.biz;

import com.alibaba.fastjson.JSONObject;
import com.engine.kq.entity.KQDutyRulesDetailEntity;
import com.engine.kq.entity.KQUsageHistoryEntity;
import com.engine.kq.log.KQLog;
import com.engine.kq.wfset.bean.DutyBalanceTimeBean;
import com.engine.kq.wfset.bean.OvertimeBalanceTimeBean;
import com.google.common.collect.Maps;
import weaver.conn.RecordSet;
import weaver.general.BaseBean;
import weaver.general.Util;
import weaver.hrm.resource.ResourceComInfo;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * 假期余额相关接口
 */
public class KQDutyBiz {

    private static KQLog logger = new KQLog();//用于记录日志信息



/*********************************************************************************zyt 新增值班***********************************************************************************/

    /**
     * 保存值班时长转换成的调休时长，当值班时长的单位与调休单位不一致时根据【值班单位】中的日折算时长转换
     *
     * @param resourceId         指定人员ID(根据人员ID判断属于哪个考勤组，根据考勤组获取值班规则ID)
     * @param date               指定日期(根据指定日期判断是节假日还是工作日还是休息日、日期格式yyyy-MM-dd)
     * @param durationOfDuty     值班时长
     * @param type               值班时长单位：0-分钟、1-小时、2-天
     *                           单位可为空(为空则默认取【值班单位】中设置的最小值班单位)
     *                           当最小值班单位与调休单位不一致时，且指定日期为工作日时使用此工作时长进行折算
     * @param requestId          值班流程的requestId(用于使用记录中可追溯至值班流程)
     * @param fromCardOrFlow     是打卡数据还是审批数据：1--打卡、2--流程
     * @param fromDateDb         值班流程表单中的值班开始日期
     * @return
     */
    public static String addExtraAmountByDis9(String resourceId, String date, String durationOfDuty
            , String type , String requestId, String fromCardOrFlow, String fromDateDb,Map<String,Object> otherParam) {
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("resourceId", resourceId);
        params.put("date", date);
        params.put("durationOfDuty", durationOfDuty);
        params.put("type", type);
        params.put("requestId", requestId);
        params.put("fromCardOrFlow", fromCardOrFlow);
        params.put("fromDateDb", fromDateDb);
        //值班转的调休明细ID(KQ_BalanceOfLeave的ID)
        String tiaoxiuId = "-1";
        try {
            String workflowid = "-1";
            RecordSet rs = new RecordSet();
            if (requestId.length() > 0 && Util.getIntValue(requestId) > 0) {
                String workflow_sql = "select workflowid from workflow_requestbase where requestid = ? ";
                rs.executeQuery(workflow_sql, requestId);
                if (rs.next()) {
                    workflowid = Util.null2s(rs.getString("workflowid"), "-1");
                }
            }
            //值班转调休是否成功
            boolean flag = false;
            //人员信息缓存类
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            //创建日期
            String createDate = Util.null2String(resourceComInfo.getCompanyStartDate(resourceId));
            //入职日期
            String companyStartDate = Util.null2String(resourceComInfo.getCompanyStartDate(resourceId));
            //如果入职日期为空，则取创建日期
            companyStartDate = "".equals(companyStartDate) ? createDate : companyStartDate;
            //分部ID
            String subCompanyId = resourceComInfo.getSubCompanyID(resourceId);
            //日期类型：1-节假日、2-工作日、3-休息日(节假日设置的优先级高于考勤组中的设置)
            int changeType = KQDutyRulesBiz.getChangeType(resourceId, date);
            //获取当前日期，当前时间
            Calendar today = Calendar.getInstance();
            //当前日期
            String currentDate = Util.add0(today.get(Calendar.YEAR), 4) + "-" +
                    Util.add0(today.get(Calendar.MONTH) + 1, 2) + "-" +
                    Util.add0(today.get(Calendar.DAY_OF_MONTH), 2);
            //当前时间
            String currentTime = Util.add0(today.get(Calendar.HOUR_OF_DAY), 2) + ":" +
                    Util.add0(today.get(Calendar.MINUTE), 2) + ":" +
                    Util.add0(today.get(Calendar.SECOND), 2);

            /****************************************************************************************************************/

            //假期类型的缓存类
            KQLeaveRulesComInfo rulesComInfo = new KQLeaveRulesComInfo();
            //[值班]的假期类型的ID
            //找到[值班]的假期类型ID
            String leaveRulesId = "";
            rulesComInfo.setTofirstRow();
            while (rulesComInfo.next()) {
                if ("1".equals(rulesComInfo.getIsEnable())) {
                    String sql = "select * from kq_LeaveRulesDetail where (isDelete is null or isDelete<>1) and distributionMode=9 and ruleId=?";
                    RecordSet recordSet = new RecordSet();
                    recordSet.executeQuery(sql, rulesComInfo.getId());
                    if (recordSet.next()) {
                        leaveRulesId = rulesComInfo.getId();
                        break;
                    }
                }
            }
            //[调休]的假期类型的最小请假单位：1-按天、2-按半天、3-按小时、4-按整天
            int minimumUnit = Util.getIntValue(rulesComInfo.getMinimumUnit(leaveRulesId), -1);
            //假期规则的缓存类
            KQLeaveRulesDetailComInfo detailComInfo = new KQLeaveRulesDetailComInfo();
            //有效期规则：0-永久有效、1-按自然年（1月1日-12月31日）、2-按入职日期起12个月、3-自定义次年失效日期、4-按天数失效
            int validityRule = Util.getIntValue(detailComInfo.getValidityRule(leaveRulesId, subCompanyId));
            //保留几位小数
            int decimalDigit = Util.getIntValue(detailComInfo.getDecimalDigit(leaveRulesId, subCompanyId), 2);

            /*如果没有设置调休的假期类型，则直接退出方法*/
            if ("".equals(leaveRulesId)) {
                logger.info("未设置调休的假期类型或未调休的假期类型下未设置改人员所在分部可用的假期规则。params=" + JSONObject.toJSONString(params));
                return "-1";
            }
            /*【调休】的假期规则的最小请假单位有误时，记录错误日志，直接返回*/
            if (minimumUnit < 1 || minimumUnit > 6) {
                logger.info("调休的请假规则的最小请假单位有误。params=" + JSONObject.toJSONString(params));
                return "-1";
            }
            /**
             * 【调休】的假期规则的有效期规则有误时，记录错误日志，直接返回
             *  原本代码  validityRule < 0 || validityRule > 6
             *  新增一个选项 增加一个按天数（工作日）规则
             */
            /******************************************************************zyt新增一个选项*************************************************************************/
            if (validityRule < 0 || validityRule > 8) {
                logger.info("调休的请假规则的有效期规则有误。params=" + JSONObject.toJSONString(params));
                return "-1";
            }
            /******************************************************************zyt新增一个选项*************************************************************************/

            /****************************************************************************************************************/

            //所属年份
            String belongYear = date.substring(0, 4);
            //失效日期
            String expirationDate = "";
            //根据有效期规则获取有效日期
            expirationDate = KQBalanceOfLeaveBiz.getExpirationDate(leaveRulesId, resourceId, belongYear, date, expirationDate);

            /****************************************************************************************************************/

            //最小值班单位：1-按天、2-按半天、3-按小时、4-按整天、5-按半小时值班、6-整小时
            int minimumUnitOfDuty = -1;
            //日折算时长
            double hoursToDay = -1.00;

            String sql = "select * from kq_DutyUnit where (isDelete is null or isDelete !=1) and id=1";
            RecordSet recordSet = new RecordSet();
            recordSet.executeQuery(sql);
            if (recordSet.next()) {
                minimumUnitOfDuty = Util.getIntValue(recordSet.getString("minimumUnit"), -1);
                hoursToDay = Util.getDoubleValue(recordSet.getString("hoursToDay"), 8.00);
            }
            /*【值班单位】的相关设置获取有误时，记录错误日志，直接返回*/
            if (minimumUnitOfDuty == -1 || hoursToDay < 0) {
                logger.info("获取到的值班单位的相关设置有误。params=" + JSONObject.toJSONString(params));
                return "-1";
            }

            BigDecimal _hoursToDay = new BigDecimal("" + hoursToDay);
            //把值班时长只按照分钟先处理一下
            BigDecimal min_durationOfDuty = new BigDecimal(Util.null2s(durationOfDuty, "0"));

            BigDecimal _durationOfDuty = new BigDecimal(Util.null2s(durationOfDuty, "0"));
            if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天
                _durationOfDuty = _durationOfDuty.divide(new BigDecimal("60").multiply(_hoursToDay), 5, RoundingMode.HALF_UP);

            } else if (KQUnitBiz.isLeaveHour(minimumUnit + "")) {     //调休单位为小时
                _durationOfDuty = _durationOfDuty.divide(new BigDecimal("60"), 5, RoundingMode.HALF_UP);
            }
            logger.info("记录一下【最小值班单位】和调休的【最小请假单位】。params=" + JSONObject.toJSONString(params));

            /*员工假期余额变更记录*/
            KQUsageHistoryBiz usageHistoryBiz = new KQUsageHistoryBiz();
            KQUsageHistoryEntity usageHistoryEntity = new KQUsageHistoryEntity();
            List<KQUsageHistoryEntity> usageHistoryEntityList = new ArrayList<KQUsageHistoryEntity>();

            Map<String, Integer> changeTypeMap = Maps.newHashMap();
            DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            Map<String, KQDutyRulesDetailEntity> overRulesDetailMap = Maps.newHashMap();
            Map<String, List<String[]>> restTimeMap = Maps.newHashMap();
            Map<String, Integer> computingModeMap = Maps.newHashMap();
            KQDutyRuleCalBiz kqDutyRuleCalBiz = new KQDutyRuleCalBiz();
            kqDutyRuleCalBiz.getDutyDataMap(resourceId, date, date, dateFormatter, changeTypeMap, overRulesDetailMap, restTimeMap, computingModeMap);

            Map<String, Object> dutyLogMap = null;
            if (otherParam != null && !otherParam.isEmpty()) {
                if (otherParam.containsKey("dutyLogMap")) {
                    dutyLogMap = (Map<String, Object>) otherParam.get("dutyLogMap");
                }
            }
            String changeType_key = date + "_" + changeType;
            KQDutyRulesDetailEntity kqDutyRulesDetailEntity = overRulesDetailMap.get(changeType_key);
            if (kqDutyRulesDetailEntity == null) {
                KQBalanceOfLeaveBiz.logOvertimeMap(dutyLogMap, changeType_key, "|值班规则为null|KQDutyRulesDetailEntity");
                logger.info("值班转调休记录日志保存失败。获取不到值班规则信息=" + JSONObject.toJSONString(changeType_key));
                return "-1";
            } else {
                logger.info("值班转调休记录。kqDutyRulesDetailEntity=" + JSONObject.toJSONString(kqDutyRulesDetailEntity));
            }
            String timepoint_key = Util.null2String(otherParam.get("timepoint_key"));
            /**
             * 判断是否允许值班补偿，若未允许，则不累加调休时长，只记录记录使用记录
             * paidLeaveEnable：是否允许值班补偿：0-不允许、1-允许
             */
            String duty_type = "";
            int paidLeaveEnable = kqDutyRulesDetailEntity.getPaidLeaveEnable();
            int paidLeaveEnableType = kqDutyRulesDetailEntity.getPaidLeaveEnableType();
            if (2 == paidLeaveEnableType) {
                if (otherParam != null && !otherParam.isEmpty()) {
                    if (otherParam.containsKey("duty_type")) {
                        duty_type = Util.null2String(otherParam.get("duty_type"));
                        if ("0".equalsIgnoreCase(duty_type)) {
                            paidLeaveEnable = 1;
                        } else if ("1".equalsIgnoreCase(duty_type)) {
                            paidLeaveEnable = 0;
                        } else {
                            paidLeaveEnable = -1;
                        }
                    }
                }
            }
            KQBalanceOfLeaveBiz.logOvertimeMap(dutyLogMap, params, timepoint_key + "|生成调休参数|params");
            KQBalanceOfLeaveBiz.logOvertimeMap(dutyLogMap, paidLeaveEnable, timepoint_key + "|是否生成调休|paidLeaveEnable");

            usageHistoryEntity = new KQUsageHistoryEntity(leaveRulesId, resourceId, requestId, resourceId, currentDate, currentTime, fromCardOrFlow.equals("1") ? "3" : "4", belongYear, "0", "0", "0", "0", "0"
                    , "0", "0", "0", "0", "0", "0", "0", "" + minimumUnit, "" + minimumUnit, "", "-1", workflowid);

            if (paidLeaveEnable != 1) {
                logger.info("未开启值班转调休，记录使用日志。params=" + JSONObject.toJSONString(params));
                /*记录使用记录*/
                usageHistoryEntity.setInsertOrUpdate("PaidLeaveEnable");
                usageHistoryEntityList.add(usageHistoryEntity);
                flag = usageHistoryBiz.save(usageHistoryEntityList);
                if (!flag) {
                    logger.info("值班转调休记录日志保存失败。params=" + JSONObject.toJSONString(params));
                }
                return "-1";
            } else {
                String paidLeaveEnableInfo = "paidLeaveEnable:" + paidLeaveEnable + ":paidLeaveEnableType:" + paidLeaveEnableType + ":duty_type:" + duty_type;
                KQBalanceOfLeaveBiz.logOvertimeMap(dutyLogMap, paidLeaveEnableInfo, "|未开启调休|paidLeaveEnable");
            }

            if (1 == paidLeaveEnableType) {
//              默认值班补偿规则
//              1-按值班时长比例转调休时长、2-按值班时长范围设置转调休时长、3-按值班的时间段设置转调休时长
                int paidLeaveEnableDefaultType = kqDutyRulesDetailEntity.getPaidLeaveEnableDefaultType();
                if (1 == paidLeaveEnableDefaultType) {
                    Map<String, String> resultMap = save_paidLeaveEnableDefaultType1(kqDutyRulesDetailEntity, _durationOfDuty, date, leaveRulesId, resourceId, belongYear, expirationDate, fromCardOrFlow);
                    if (!resultMap.isEmpty()) {
                        return KQBalanceOfLeaveBiz.handleUsageHistory(resultMap, params, usageHistoryEntity);
                    }
                } else if (2 == paidLeaveEnableDefaultType) {
                    int ruleDetailid = kqDutyRulesDetailEntity.getId();
                    if (ruleDetailid > 0) {
                        Map<String, String> resultMap = save_paidLeaveEnableDefaultType2(date, leaveRulesId, resourceId, belongYear, expirationDate, fromCardOrFlow, ruleDetailid, min_durationOfDuty, minimumUnit, _hoursToDay);
                        if (!resultMap.isEmpty()) {
                            return KQBalanceOfLeaveBiz.handleUsageHistory(resultMap, params, usageHistoryEntity);
                        }
                    }
                }
            }
        } catch (Exception e) {
            logger.info("值班转调休出错。params=" + JSONObject.toJSONString(params));
            new BaseBean().writeLog(e);
        }
        return tiaoxiuId;
    }

/**************************************************************************************zyt******************************************************************************/



    /********************************************************************************************zyt********************************************************************/
    /**
     * 按值班时长比例转调休时长
     * @param kqDutyRulesDetailEntity
     * @param _durationOfDuty
     * @param date
     * @param leaveRulesId
     * @param resourceId
     * @param belongYear
     * @param expirationDate
     * @param fromCardOrFlow
     * @return
     */
    private static Map<String,String> save_paidLeaveEnableDefaultType1(
            KQDutyRulesDetailEntity kqDutyRulesDetailEntity,
            BigDecimal _durationOfDuty, String date, String leaveRulesId, String resourceId,
            String belongYear, String expirationDate, String fromCardOrFlow) {
        Map<String,String> resultMap = Maps.newHashMap();

        String tiaoxiuId = "-1";
        boolean flag = false;
        RecordSet recordSet = new RecordSet();
        String extraAmount = "";
        /**
         * 计算调休时长并存入调休余额中
         */
        BigDecimal _lenOfLeave = new BigDecimal("" + kqDutyRulesDetailEntity.getLenOfLeave());
        BigDecimal _lenOfDuty = new BigDecimal("" + kqDutyRulesDetailEntity.getLenOfDuty());
        BigDecimal durationOfLeave = _durationOfDuty.multiply(_lenOfLeave).divide(_lenOfDuty, 5, RoundingMode.HALF_UP);
        extraAmount = durationOfLeave.setScale(5, RoundingMode.HALF_UP).toPlainString();

        if (durationOfLeave.doubleValue() <= 0) {
            extraAmount = "0.0";
        }
        /*插入调休时长*/
        String _belongYear = date.substring(0, 4);
        String _belongMonth = date.substring(5, 7);
        String sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete) " +
                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0);
        if (!flag) {
            resultMap.put("status", "-2");
            return resultMap;
        }
        //获取刚才插入的调休明细的ID
        sql = "select max(id) from kq_balanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?";
        recordSet.executeQuery(sql, leaveRulesId, resourceId, belongYear);
        if (recordSet.next()) {
            tiaoxiuId = recordSet.getString(1);
        }
        resultMap.put("status", "1");
        resultMap.put("tiaoxiuId", tiaoxiuId);
        resultMap.put("extraAmount", extraAmount);
        return resultMap;
    }


    /**************************************************************************************************zyt***********************************************************************************/


    /**
     * 按值班时长范围设置转调休时长
     * @param date
     * @param leaveRulesId
     * @param resourceId
     * @param belongYear
     * @param expirationDate
     * @param fromCardOrFlow
     * @param ruleDetailid
     * @param min_durationOfDuty
     * @param minimumUnit
     * @param _hoursToDay
     * @return
     */
    private static Map<String, String> save_paidLeaveEnableDefaultType2(
            String date, String leaveRulesId, String resourceId,
            String belongYear, String expirationDate, String fromCardOrFlow, int ruleDetailid,
            BigDecimal min_durationOfDuty, int minimumUnit, BigDecimal _hoursToDay) {
        Map<String,String> resultMap = Maps.newHashMap();

        String tiaoxiuId = "-1";
        boolean flag = false;
        RecordSet recordSet = new RecordSet();
        String extraAmount = "";

        int dutylength_i = -1;
        KQDutyRulesBiz kqDutyRulesBiz = new KQDutyRulesBiz();
        Map<String,List<String>> balanceLengthDetailMap = kqDutyRulesBiz.getBalanceLengthDetailMap(ruleDetailid);
        if(balanceLengthDetailMap != null && !balanceLengthDetailMap.isEmpty()){
            List<String> dutylengthList = balanceLengthDetailMap.get("dutylengthList");
            for(int i = 0 ; i < dutylengthList.size() ; i++){
                String dutylength = Util.null2s(dutylengthList.get(i),"");
                if(dutylength.length() == 0){
                    continue;
                }
                BigDecimal b_60Mins = new BigDecimal(60);
                BigDecimal b_dutylength = new BigDecimal(dutylength).multiply(b_60Mins);
                if(min_durationOfDuty.compareTo(b_dutylength) >= 0){
                    dutylength_i = i;
                    break;
                }
            }
            if(dutylength_i  > -1){
                List<String> balancelengthList = balanceLengthDetailMap.get("balancelengthList");
                if(balancelengthList.size() > dutylength_i){
                    String balancelength = balancelengthList.get(dutylength_i);
                    BigDecimal b_balancelength = new BigDecimal(balancelength);
                    if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天
                        b_balancelength = b_balancelength.divide(_hoursToDay, 5, RoundingMode.HALF_UP);

                    } else if (KQUnitBiz.isLeaveHour(minimumUnit+"")) {//调休单位为小时
                    }
                    extraAmount = Util.null2s(b_balancelength.toPlainString(), "0");
                }
            }
        }
        new KQLog().info("save_paidLeaveEnableDefaultType2 balanceLengthDetailMap:"+balanceLengthDetailMap
                +":min_durationOfDuty:"+min_durationOfDuty+":extraAmount:"+extraAmount);

        if (Util.getDoubleValue(extraAmount) <= 0) {
            extraAmount = "0.0";
        }
        if(dutylength_i < 0){
            extraAmount = "0.0";
        }
        /*插入调休时长*/
        String _belongYear = date.substring(0, 4);
        String _belongMonth = date.substring(5, 7);
        String sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete) " +
                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0);
        if (!flag) {
            resultMap.put("status", "-2");
            return resultMap;
        }
        //获取刚才插入的调休明细的ID
        sql = "select max(id) from kq_balanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?";
        recordSet.executeQuery(sql, leaveRulesId, resourceId, belongYear);
        if (recordSet.next()) {
            tiaoxiuId = recordSet.getString(1);
        }
        resultMap.put("status", "1");
        resultMap.put("tiaoxiuId", tiaoxiuId);
        resultMap.put("extraAmount", extraAmount);
        return resultMap;
    }




    /**
     * 按加班的时间段设置转调休时长
     * @param date
     * @param leaveRulesId
     * @param resourceId
     * @param belongYear
     * @param expirationDate
     * @param fromCardOrFlow
     * @param ruleDetailid
     * @param dutyBalanceTimeBean
     * @param list_index
     * @param minimumUnit
     * @param _hoursToDay
     * @param overtimeLogMap
     * @param timepoint_key
     * @return
     */
    private static Map<String, String> save_paidLeaveEnableDefaultType3(String date,
                                                                        String leaveRulesId, String resourceId, String belongYear, String expirationDate,
                                                                        String fromCardOrFlow, int ruleDetailid, DutyBalanceTimeBean dutyBalanceTimeBean,
                                                                        int list_index, int minimumUnit, BigDecimal _hoursToDay,
                                                                        Map<String, Object> overtimeLogMap, String timepoint_key) {
        Map<String,String> resultMap = Maps.newHashMap();

        String tiaoxiuId = "-1";
        boolean flag = false;
        RecordSet recordSet = new RecordSet();
        String extraAmount = "";

        KQDutyRulesBiz kqDutyRulesBiz = new KQDutyRulesBiz();
        Map<String, List<String>> balanceLengthDetailMap = kqDutyRulesBiz.getBalanceTimeDetailMap(ruleDetailid);

        int timepoint_min = dutyBalanceTimeBean.getTimepoint_mins();
        List<String> lenOfDutyList = balanceLengthDetailMap.get("lenOfDutyList");
        List<String> lenOfLeaveList = balanceLengthDetailMap.get("lenOfLeaveList");
        String lenOfDuty = lenOfDutyList.get(list_index);
        String lenOfLeave = lenOfLeaveList.get(list_index);

        BigDecimal _timepoint_min = new BigDecimal(Util.null2s(""+timepoint_min, "0"));
        BigDecimal _lenOfLeave = new BigDecimal(lenOfLeave);
        BigDecimal _lenOfDuty = new BigDecimal(lenOfDuty);
        BigDecimal durationOfLeave = _timepoint_min.multiply(_lenOfLeave).divide(_lenOfDuty, 5, RoundingMode.HALF_UP);

        if (minimumUnit == 1 || minimumUnit == 2 || minimumUnit == 4) {//调休单位为天
            durationOfLeave = durationOfLeave.divide(new BigDecimal("60").multiply(_hoursToDay), 5, RoundingMode.HALF_UP);

        } else if (KQUnitBiz.isLeaveHour(minimumUnit+"")) {//调休单位为小时
            durationOfLeave = durationOfLeave.divide(new BigDecimal("60"), 5, RoundingMode.HALF_UP);
        }

        extraAmount = durationOfLeave.setScale(5, RoundingMode.HALF_UP).toPlainString();
        String paidLeaveEnableDefaultType3 = "minimumUnit:"+minimumUnit+":durationOfLeave:"+durationOfLeave
                +":_lenOfLeave:"+_lenOfLeave+":_lenOfDuty:"+_lenOfDuty+":_timepoint_min:"+_timepoint_min+":_hoursToDay:"+_hoursToDay;
        KQBalanceOfLeaveBiz.logOvertimeMap(overtimeLogMap,paidLeaveEnableDefaultType3,timepoint_key+"|生成调休|save_paidLeaveEnableDefaultType3");

        if (Util.getDoubleValue(extraAmount) <= 0) {
            resultMap.put("status", "-1");
            return resultMap;
        }
        /*插入调休时长*/
        String _belongYear = date.substring(0, 4);
        String _belongMonth = date.substring(5, 7);
        String sql = "insert into kq_balanceOfLeave(leaveRulesId,resourceId,belongYear,belongMonth,baseAmount,tiaoxiuamount,usedAmount,baseAmount2,extraAmount2,usedAmount2,status,expirationDate,effectiveDate,overtimeType,isDelete) " +
                "values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        flag = recordSet.executeUpdate(sql, leaveRulesId, resourceId, _belongYear, _belongMonth, 0, extraAmount, 0, 0, 0, 0, 0, expirationDate, date, fromCardOrFlow.equals("0") ? "3" : "4", 0);
        if (!flag) {
            resultMap.put("status", "-2");
            return resultMap;
        }
        //获取刚才插入的调休明细的ID
        sql = "select max(id) from kq_balanceOfLeave where leaveRulesId=? and resourceId=? and belongYear=?";
        recordSet.executeQuery(sql, leaveRulesId, resourceId, belongYear);
        if (recordSet.next()) {
            tiaoxiuId = recordSet.getString(1);
        }
        resultMap.put("status", "1");
        resultMap.put("tiaoxiuId", tiaoxiuId);
        resultMap.put("extraAmount", extraAmount);
        return resultMap;
    }
}
